<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 14-11-18
 * Time: 下午3:25
 */

class Lesson_Discussion extends Eloquent
{
    public function lesson()
    {
        return $this->belongsTo('Lesson', 'lesson_id', 'id');
    }

    public function creater()
    {
        return $this->hasOne('User', 'id', 'creater_id');
    }

    public function reply()
    {
        return $this->hasMany('Lesson_Discussion_Reply', 'discussion_id', 'id');
    }

    public static function getLessonDiscussions($lessonId, array $keys = null)
    {
        return DB::table('lesson_discussions')
            ->where('lesson_id', $lessonId)
            ->leftJoin('users', 'creater_id', '=', 'users.id')
            ->select('lesson_discussions.id AS id',
                'title', 'content',
                'lesson_discussions.updated_at AS updated_at',
                'lesson_discussions.created_at AS created_at',
                'users.username AS creater_username',
                'users.head_image AS creater_head_image',
                'users.id AS creater_id')
            ->get($keys);
    }

    public static function getLessonDiscussionsOrFail($lessonId, array $keys = null)
    {
        $rep = static::getLessonDiscussions($lessonId, $keys);

        if( count($rep) === 0 ){
            throw new \Illuminate\Database\Eloquent\ModelNotFoundException;
        }

       return $rep;
    }

    public static function findDiscussionOnLesson($lessonId, $discussionId)
    {
        return static::where('lesson_id', $lessonId)->where('id', $discussionId)->first();
    }

    public static function findDiscussionOnLessonOrFail($lessonId, $discussionId)
    {
        return static::where('lesson_id', $lessonId)->where('id', $discussionId)->firstOrFail();
    }

    protected $guarded = ['id'];

    protected $table = 'lesson_discussions';
}